import subprocess
import requests
import os
import zipfile
import shutil

# 获取Edge浏览器的大版本号
def get_edge_version():
    # Windows系统示例
    process = subprocess.run(['powershell', '(Get-ItemProperty -Path HKCU:\\Software\\Microsoft\\Edge\\BLBeacon -Name version).version'], shell=True,capture_output=True, text=True)
    version = process.stdout.strip()
    return version

# 下载对应的WebDriver
def download_driver(version,progress_signal):
    # 构建下载链接，这里需要根据实际版本号来构建
    url = f'https://msedgedriver.azureedge.net/{version}/edgedriver_win64.zip'
    try:
        # 获取文件大小
        response = requests.head(url)
        if response.status_code != 200:
            return None  # 如果请求头返回错误，返回 None
        
        total_size = int(response.headers.get('Content-Length', 0))  # 获取文件的总大小
        if total_size == 0:
            return None  # 如果没有文件大小信息，返回 None

        # 开始流式下载文件
        response = requests.get(url, stream=True)
        with open('edgedriver_win64.zip', 'wb') as file:
            downloaded = 0
            for chunk in response.iter_content(chunk_size=1024):  # 每次下载1KB数据
                if chunk:
                    file.write(chunk)
                    downloaded += len(chunk)
                    progress = int((downloaded / total_size) * 100)  # 计算下载进度
                    progress_signal.emit(progress)  # 发射信号更新进度条
        return 'edgedriver_win64.zip'
    except Exception as e:
        print(f"下载失败: {e}")
        return None

# 自动解压功能
def unzip_file(zip_path, extract_to):
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(extract_to)

# 删除文件或目录
def delete_file_or_dir(path):
    if os.path.isfile(path):
        os.remove(path)
    elif os.path.isdir(path):
        shutil.rmtree(path)
